import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'

const service = axios.create({
  // 使用mock数据调试
  baseURL: process.env.VUE_APP_BASE_API,

  // 使用后端接口调试
  // baseURL: 'http://localhost:31436',

  // baseURL: 'http://106.52.13.180',

  // withCredentials: true,
  timeout: 5000,
})

service.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + store.getters.token
    }
    return config
  },
  (error) => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const res = response.data
    console.log('response res', res)
    if (res.code !== 0) {
      Message({
        message: res.data || '接口返回异常',
        type: 'error',
        duration: 5 * 1000,
      })

      if (res.code === 401 || res.code === 403) {
        MessageBox.confirm('请求被拒绝，如果您已登出，请重新登陆系统', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning',
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.data || 'Error'))
    } else {
      return res
    }
  },
  (error) => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000,
    })
    return Promise.reject(error)
  }
)

export default service
